import React, { useState, Fragment, useEffect } from 'react';
import { Form, Input, Icon, Button, message, Spin } from 'antd';
import { FormComponentProps } from 'antd/lib/form';
import {
  requestAddFault,
  requestGetFaultInfo,
  GetFaultReturnData,
  requestEditFault
} from '../../api/index';
import './index.css';
import errorHandler from '../../api/utils/requestErrorHandler';
import { RouteComponentProps } from 'react-router-dom';
import RichText from '../../components/RichText';
type Props = FormComponentProps & RouteComponentProps<{ id: string }, {}, { mode: 'add' | 'edit' }>;
interface ReasonSolution {
  name: string;
  solution: string;
}

const FormItem = Form.Item;
let uid = 0;

const initFault = {
  _id: '',
  name: '',
  reasons: []
};

const AddData = (props: Props): JSX.Element => {
  const {
    match: {
      params: { id }
    },
    location: {
      state: { mode }
    },
    form: { getFieldDecorator, getFieldsValue, validateFields }
  } = props;

  const [keys, setKeys] = useState<number[]>([uid]);

  const [faultInfo, setFaultInfo] = useState<GetFaultReturnData>(initFault);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    const fetchData = async (): Promise<void> => {
      try {
        setLoading(true);
        const { data } = await requestGetFaultInfo(id);
        let i = 0;
        const arr = [];
        while (i <= data.reasons.length - 1) {
          arr.push(i);
          i++;
        }
        uid = data.reasons.length - 1;
        setKeys(arr);
        setFaultInfo(data);
      } catch (error) {
        errorHandler(error);
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchData();
    }
  }, [id]);

  const add = (): void => {
    setKeys([...keys, ++uid]);
  };

  const remove = (v: number): void => {
    setKeys(keys.filter((k) => k !== v));
  };

  const back = (): void => {
    props.history.goBack();
  };

  const formItems = keys.map((k, index) => (
    <Fragment key={k}>
      <div>
        可能因素{index + 1} &nbsp;
        {keys.length !== 1 ? (
          <Icon className="minus-icon" type="minus-circle-o" onClick={remove.bind(null, k)}></Icon>
        ) : null}
        {keys.length === index + 1 ? <Icon type="plus-circle-o" onClick={add}></Icon> : null}
      </div>
      <FormItem>
        {getFieldDecorator(`reason_${k}`, {
          rules: [{ required: true, message: '请输入故障原因' }],
          initialValue: faultInfo.reasons[k] ? faultInfo.reasons[k].name : null
        })(<Input placeholder="故障原因" size="large" />)}
      </FormItem>
      <FormItem>
        {getFieldDecorator(`solution_${k}`, {
          rules: [{ required: true, message: '请输入解决方案' }],
          initialValue: faultInfo.reasons[k] ? faultInfo.reasons[k].solution : null
        })(<RichText id={k} />)}
      </FormItem>
    </Fragment>
  ));

  const save = async (): Promise<void> => {
    validateFields(async (error) => {
      if (error) {
        return;
      }

      const sourceData = getFieldsValue();

      const values = { ...sourceData };
      delete values.name;

      const cache = {};
      const data: ReasonSolution[] = [];

      Object.keys(values).forEach((k) => {
        const count = k.split('_')[1];

        if (cache[count]) {
          return;
        }

        data.push({ name: values[`reason_${count}`], solution: values[`solution_${count}`] });
        cache[count] = true;
      });

      try {
        if (mode === 'edit') {
          await requestEditFault({ id, name: sourceData.name, reasons: data });
        } else {
          await requestAddFault({ name: sourceData.name, reasons: data });
        }

        message.success('操作成功');
        setTimeout(() => {
          window.location.reload();
        }, 600);
      } catch (error) {
        errorHandler(error);
      }
    });
  };

  if (loading) {
    return <Spin />;
  }

  return (
    <Form>
      <FormItem>
        {getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入故障现象' }],
          initialValue: faultInfo.name
        })(<Input placeholder="故障现象" size="large" />)}
      </FormItem>
      {formItems}
      <FormItem>
        <div className="center">
          <Button type="primary" onClick={back}>
            取消
          </Button>
          <Button type="primary" onClick={save}>
            保存
          </Button>
        </div>
      </FormItem>
    </Form>
  );
};

export default Form.create()(AddData);
